package com.example.hibernate.i.one2one_fk;

import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.junit.Test;

import com.example.hibernate.utils.HibernateUtils;

public class TestApp {
	
	@Test
	public void testSave(){
		User user = new User();
		Address addr = new Address();
		
		user.setUsername("ipeng2012");
		user.setPassword("a123456a");
		
		addr.setCity("GZ");
		addr.setStreet("HZ");
		addr.setZipcode("520000");
		
		user.setAddress(addr);
		addr.setUser(user);
		
		Session session = HibernateUtils.openSession();
		session.beginTransaction();
		
		session.save(addr);
		session.save(user);
		
		session.getTransaction().commit();
		
	}
	
	
	@Test
	public void testGet(){
		Session session = HibernateUtils.openSession();
		session.beginTransaction();
		
		User user = (User) session.get(User.class, 5L);
		Address address = (Address) session.get(Address.class, 3L);
		
		Hibernate.initialize(user.getAddress());
		
		session.getTransaction().commit();
		
		System.out.println(user);
//		org.hibernate.LazyInitializationException
		System.out.println(user.getAddress());
		
		System.out.println("----------");
		System.out.println(address);
		System.out.println(address.getUser());
	}
	
	@Test
	public void testUpdate(){
		
	}
	
	@Test
	public void testDeleteUser(){
		Session session = HibernateUtils.openSession();
		session.beginTransaction();
		
		User user = (User) session.get(User.class, 5L);
		session.delete(user);
		
		session.getTransaction().commit();
	}
	
	@Test
	public void testDeleteAddr(){
		Session session = HibernateUtils.openSession();
		session.beginTransaction();
		
		Address address = (Address) session.get(Address.class, 7L);
		address.getUser().setAddress(null);
		session.delete(address);
		session.getTransaction().commit();
	}
}
